package com.megan.design.utilts;

import java.math.BigDecimal;

/**
 * 加减乘除处理丢失精度问题
 * Created by 17936 on 2017/9/3.
 */
public class BigDecimalUtil {
    private BigDecimalUtil(){

    }
    //加
    public static BigDecimal add(double v1, double v2){
        BigDecimal b1= new BigDecimal(Double.toString(v1));
        BigDecimal b2= new BigDecimal(Double.toString(v2));
        return b1.add(b2);
    }

    //减
    public static BigDecimal sub(double v1, double v2){
        BigDecimal b1= new BigDecimal(Double.toString(v1));
        BigDecimal b2= new BigDecimal(Double.toString(v2));
        return b1.subtract(b2);
    }
    //乘
    public static BigDecimal mul(double v1, double v2){
        BigDecimal b1= new BigDecimal(Double.toString(v1));
        BigDecimal b2= new BigDecimal(Double.toString(v2));
        return b1.multiply(b2);
    }    //除
    public static BigDecimal div(double v1, double v2){
        BigDecimal b1= new BigDecimal(Double.toString(v1));
        BigDecimal b2= new BigDecimal(Double.toString(v2));
        //除不尽的情况
        return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//四舍五入，保留2位小数
    }
}
